<?php

namespace App\Http\Controllers\Api;

use App\Models\Apiuser;
use App\Models\Renting;
use http\Client;
use http\Env\Response;
use Illuminate\Http\Request;

class loginController extends BaseController
{
  public function login(Request $request)
  {
      //获取 异常
      try {
          $this->validate($request,[
              "username"=>"required",
              "password"=>"required",
          ]);
      }
      catch (\Exception $exception){
          return  $this->reErJson('账号和密码不能为空！');
      }
      //验证账号和密码是否正确
      $bool = auth()->guard('apiweb')->attempt($request->all());
      if($bool){
          //生成token 获取用户模型
          $userModel = auth()->guard('apiweb')->user();
          //判断接口当前 是超过2000次
          if($userModel->click>2000){
              return  $this->reErJson('请求次数超过2000次！',1002,500);
          }
          $token = $userModel->createToken('api')->accessToken;
          //设置请求次数 加1 读写交给数据库 保存数据的原子性 一致性
          $userModel->increment('click');
          //返回 token
          return response()->json(['expire'=>7200,'token'=>$token]);
      }else{
          return  $this->reErJson('账号和密码不正确！');
      }
  }
  //小程序登录
  public function  wxlogin(Request $request){
        $appid ="123456";
        $appSecret ="qsadaqwe123";
        $code = $request->get('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        //替换参数
        $url = sprintf($url,$appid,$appSecret,$code);
        //发起get请求 声明请求客户端 referer 不验证https  不验证证书
        $Client= new Client(['timeout'=>5,'referer'=>false]);
        $response = $Client->get($url);
        $ret = (string)$response->getBody();
        //保存opneid
        $userData = json_decode($ret,true);
        if($userData['openid']){
            Renting::updateOrCreate(
                ['openid' => $userData['openid']], //查询条件
                ['openid' => $userData['openid']]  //添加或者修改的数据
            );
        }
        return $ret;
  }
}
